import type { EChartsOption } from 'echarts'

import type { UnwrapArray } from '@/types'

import type { PositionType } from '../types'
import { getLegendPos } from '../utils'

export interface HookOptions {
  dataSource: {
    title?: string
    data: {
      name: string
      value: number
      itemStyle: { color: string }
    }[]
  }
  legendPosition?: PositionType
  total?: number
  valueFormatter?: (value: any) => string
  labelFormatter?: (value: any) => string
}

export default function useFunnelCharts(options: HookOptions) {
  options.legendPosition = options.legendPosition || 'tl'

  // 生成图例数据
  function generateLegendData(): NonNullable<
    UnwrapArray<EChartsOption['legend']>
  >['data'] {
    return options.dataSource.data?.map(item => {
      return {
        name: item.name,
        textStyle: {
          color: item.itemStyle.color
        }
      }
    })
  }

  const chartsOptions = computed(() => {
    return {
      grid: {
        left: 0,
        right: 0
      },
      tooltip: {
        trigger: 'item',
        borderColor: '#DFE2E5',
        borderWidth: 1,
        formatter(params: any) {
          return `
            <div class="pie-tooltip">
              ${
                options.dataSource.title
                  ? `<div class="title">${options.dataSource.title}</div>`
                  : ''
              }
              <div class="wrap">
                <div style="background-color: ${params.color}"></div>
                <div class="name">${params.data.name}</div>
                <div class="value">
                  ${
                    options.valueFormatter
                      ? options.valueFormatter(params.dataIndex)
                      : params.data.value
                  }
                </div>
              </div>
            </div>
          `
        }
      },
      legend: {
        ...getLegendPos(options.legendPosition!),
        data: generateLegendData(),
        itemGap: 16,
        itemWidth: 12,
        itemHeight: 8
      },
      series: [
        {
          name: options.dataSource.title,
          type: 'funnel',
          min: 0,
          minSize: 48,
          maxSize: '100%',
          width: '60%',
          top: 54,
          bottom: 0,
          left: 'center',
          lastPoint: 'arrow',
          label: {
            show: true,
            position: 'inside',
            color: '#fff',
            fontSize: 16,
            fontFamily: 'BebasNeue',
            formatter: val => {
              if (options.labelFormatter) {
                //@ts-ignore
                return options.labelFormatter(val.data?.value)
              }
              //@ts-ignore
              return val.data?.value
            }
          },
          itemStyle: {
            height: 48,
            borderColor: 'none'
          },
          data: options.dataSource.data
        }
      ]
    } as EChartsOption
  })

  return {
    options: chartsOptions
  }
}
